import torch
import torch.nn as nn
import math
print(torch.__version__)  # 输出示例：2.7.1

class PositionalEncoding(nn.Module):
    def __init__(self, d_model, max_len=500):
        super().__init__()
        pe = torch.zeros(max_len, d_model)
        pos = torch.arange(0, max_len).unsqueeze(1)
        div = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(pos * div)
        pe[:, 1::2] = torch.cos(pos * div)
        self.pe = pe.unsqueeze(1)  # [max_len, 1, d_model]

    def forward(self, x):
        return x + self.pe[:x.size(0)]

class SimpleTransformer(nn.Module):
    def __init__(self, input_dim, d_model=512, nhead=8, num_layers=6, num_classes=10):
        super().__init__()
        self.embedding = nn.Embedding(input_dim, d_model)
        self.pos_encoder = PositionalEncoding(d_model)
        encoder_layer = nn.TransformerEncoderLayer(d_model, nhead,batch_first=True)
        self.transformer = nn.TransformerEncoder(encoder_layer, num_layers)
        self.classifier = nn.Linear(d_model, num_classes)

    def forward(self, src):  # src: [seq_len, batch_size]
        x = self.embedding(src)  # [seq_len, batch, d_model]
        x = self.pos_encoder(x)
        x = self.transformer(x)  # [seq_len, batch, d_model]
        x = x.mean(dim=0)        # [batch, d_model]  (mean pooling)
        return self.classifier(x)

# 使用示例
vocab_size = 1000
model = SimpleTransformer(input_dim=vocab_size)

src = torch.randint(0, vocab_size, (20, 32))  # [seq_len, batch]
out = model(src)  # [batch, num_classes]
print(out.shape)
